package com.lst.servlet;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.ClientOnlineCourseMapper;
import com.lst.entity.request.PlanReqPara;
import com.lst.entity.response.PlanCourseResPara;
import com.lst.model.ClientOnlineCourse;
import com.lst.model.OnlineCourse;
import com.lst.model.Plan;
import com.lst.model.PlanCourse;
import com.lst.model.WenwInfo;
import com.lst.service.OnlineCourseService;
import com.lst.service.PlanCourseService;
import com.lst.service.PlanService;
import com.lst.service.WenwInfoService;
import com.lst.utils.RequestUtils;
import com.lst.utils.TrainingDay;


/**
 * @ClassName: PlanDetailServlet
 * @Description: 我的功夫计划详情接口
 * 
 */
public class PlanFirstServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private PlanCourseService planCourseService = ctx.getBean(PlanCourseService.class);
	private PlanService planService = ctx.getBean(PlanService.class);
	private OnlineCourseService onlineCourseService = ctx.getBean(OnlineCourseService.class);
	private WenwInfoService wenwInfoService = ctx.getBean(WenwInfoService.class);
	
	 @Autowired
	 private ClientOnlineCourseMapper clientOnlineCourseMapper = ctx.getBean(ClientOnlineCourseMapper.class);
	 
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		PlanCourseResPara resPara = new PlanCourseResPara();

		try {
			PlanReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
     		Integer userid = Integer.valueOf(reqPara.getUserid());
     		
     		Plan plan=planService.selectByUser(userid);
     	   if(plan!=null){
     		   resPara.setPlanId(plan.getId());
     		//训练天数为10天，连续3个训练日没练，计划过期； 训练天数为14天，连续4个训练日没练，计划过期； 训练天数为18天，连续5个训练日没练，计划过期； 训练天数为22天，连续6个训练日没练，计划过期；
     		   Map<String,Object> countMap=new HashMap<String,Object>();
     		  countMap.put("planId", plan.getId());
     		  countMap.put("trainDate", startDate);
     		  int countNum=planCourseService.countByMap( countMap);
     		  int num1=plan.getFrequency();
     		  int num2=0;
     		  if(num1==10){
     			  num2=3;
     		  }
     		 if(num1==14){
    			  num2=4;
    		  }
     		 if(num1==18){
    			  num2=5;
    		  }
     		 if(num1==22){
    			  num2=6;
    		  }
     		//  System.out.println("没训练日："+countNum);
     		  if(countNum!=0 && countNum>=num2){
     			 resPara.setIsHasPlan(3);//过期
     		  }else if(countNum==0){
     			 int countNum2=planCourseService.countByMap2( countMap);
     			// System.out.println("之前总的没训练日："+countNum2);
     			 if(countNum2>=num2){
     			  resPara.setIsHasPlan(3);//过期
     			 }else{
     				gain(resPara,plan.getId(),plan.getStartTime(),num1,userid); 
     			 }
     		  }else{
     			 gain(resPara,plan.getId(),plan.getStartTime(),num1,userid); 
     		  }
     		  
     	   }else{
     		  Map<String,Object> rusultMap=new HashMap<String,Object>();
     		  rusultMap.put("createUser", userid);
     		  rusultMap.put("orderByClause", "md.createDate desc");
     		  List<Plan> planList=planService.queryByList(rusultMap);
     		  if(planList!=null && planList.size()>0){
     			 Plan plan2=planList.get(0);
     			 if(plan2.getStatus()==2){
     				 resPara.setIsHasPlan(2);
     			 }else{
     				resPara.setIsHasPlan(4);
     			 }
     		  }else{
     			 resPara.setIsHasPlan(4);
     		  }
     	   }
			
			resPara.setCode(CommCode.M_Y000000);
			resPara.setMessage(CommCode.M_Y000001);
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
	//		logger.info("PlanFirstServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

	//		logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public PlanReqPara getReqPara(HttpServletRequest request) {

		PlanReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new PlanReqPara());

			reqPara = (PlanReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			
	//		logger.info("reqPara userid:" + userid);
		
	        reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		PlanReqPara cdReqPara = (PlanReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

       if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else {
			flag = true;
		}

		return  flag;
	}
	/**
	 * 有训练计划，获得今天训练课程或者文章
	 * @param resPara
	 * @param pid
	 * @param startDate
	 * @param userid
	 * @throws Exception
	 */
	private void gain(PlanCourseResPara resPara,Integer pid,Date dateStart,int num,Integer userid) throws Exception{
		  resPara.setIsHasPlan(1);//标识有训练计划
		  Map<String,Object> reMap=new HashMap<String, Object>();
		  reMap.put("createUser", userid);
		  reMap.put("planId", pid);
		  reMap.put("orderByClause", "md.trainDate");
		  List<PlanCourse> planCourseList=planCourseService.selectByUser2(reMap);
		  List<WenwInfo> wenwInfoList=new ArrayList<WenwInfo>();//根据课程查询文章集合
		  if(planCourseList!=null && planCourseList.size()>0){
			  for(PlanCourse planCourse:planCourseList){
				  Date date=planCourse.getTrainDate();
				  Long trainDate2=date.getTime();
				  planCourse.setTrainDate2(trainDate2);
				  OnlineCourse onlineCourse=onlineCourseService.selectByPrimaryKey(planCourse.getCourseId());
			  	    //判断是否添加到我的功夫
				 	
					 	 Map<String, Object> reqmap = new HashMap<String, Object>();
					 	 reqmap.put("clientid", userid);
					 	 reqmap.put("courseid", onlineCourse.getId());
					 	 ClientOnlineCourse clientOnlineCourse=clientOnlineCourseMapper.selectByMap(reqmap);
					 	 if(clientOnlineCourse!=null){
					 	    onlineCourse.setIsAdd(true);
					 	   }
				 
				  planCourse.setOnlineCourse(onlineCourse);
				  WenwInfo wenInfo=wenwInfoService.selectByPrimaryKey(onlineCourse.getArticleNum());
				  wenwInfoList.add(wenInfo);
			  }
		  }
		  resPara.setPlanCourseList( planCourseList);//查询所有训练安排
		  
		//查询训练总数与已经完成数量
		 Map<String,Object> tMap1=new HashMap<String, Object>();
		 tMap1.put("planId", pid);
		 int totalNum=planCourseService.countByStatus(tMap1);//总训练数
		 resPara.setTotalNum(totalNum);
		 
		 Map<String,Object> tMap2=new HashMap<String, Object>();
		 tMap2.put("planStatus", 2);
		 tMap2.put("planId", pid);
		 int completeNum=planCourseService.countByStatus(tMap2);//完成训练数
		 resPara.setCompleteNum(completeNum); 
		 
		 //休息日文章推荐
	//	 List<Map<String,WenwInfo>> wenList=new ArrayList<Map<String,WenwInfo>>();
		 Map<String,WenwInfo> map=new LinkedHashMap<String,WenwInfo>();
		 List<String> restDateList=TrainingDay.train2(dateStart,num);	//获得4周的休息日
		 if(num==10){
			 map.put(restDateList.get(0), wenwInfoList.get(1));
			 map.put(restDateList.get(1), wenwInfoList.get(1));
			 map.put(restDateList.get(2), wenwInfoList.get(2));
			 map.put(restDateList.get(3), wenwInfoList.get(2));
			 map.put(restDateList.get(4), wenwInfoList.get(3));
			 map.put(restDateList.get(5), wenwInfoList.get(3));
			 map.put(restDateList.get(6), wenwInfoList.get(4));
			 map.put(restDateList.get(7), wenwInfoList.get(4));
			 map.put(restDateList.get(8), wenwInfoList.get(5));
			 map.put(restDateList.get(9), wenwInfoList.get(5));
			 map.put(restDateList.get(10), wenwInfoList.get(6));
			 map.put(restDateList.get(11), wenwInfoList.get(7));
			 map.put(restDateList.get(12), wenwInfoList.get(7));
			 map.put(restDateList.get(13), wenwInfoList.get(8));
			 map.put(restDateList.get(14), wenwInfoList.get(8));
			 map.put(restDateList.get(15), wenwInfoList.get(9));
			 map.put(restDateList.get(16), wenwInfoList.get(9));
			 map.put(restDateList.get(17), wenwInfoList.get(9));
//			 wenList.add(map);
		 }
		 if(num==14){
			 map.put(restDateList.get(0), wenwInfoList.get(1));
			 map.put(restDateList.get(1), wenwInfoList.get(1));
			 map.put(restDateList.get(2), wenwInfoList.get(2));
			 map.put(restDateList.get(3), wenwInfoList.get(3));
			 map.put(restDateList.get(4), wenwInfoList.get(4));
			 map.put(restDateList.get(5), wenwInfoList.get(5));
			 map.put(restDateList.get(6), wenwInfoList.get(6));
			 map.put(restDateList.get(7), wenwInfoList.get(7));
			 map.put(restDateList.get(8), wenwInfoList.get(8));
			 map.put(restDateList.get(9), wenwInfoList.get(9));
			 map.put(restDateList.get(10), wenwInfoList.get(10));
			 map.put(restDateList.get(11), wenwInfoList.get(11));
			 map.put(restDateList.get(12), wenwInfoList.get(12));
			 map.put(restDateList.get(13), wenwInfoList.get(13));
	//		 wenList.add(map);
		 }
		 if(num==18){
			 map.put(restDateList.get(0), wenwInfoList.get(1));
			 map.put(restDateList.get(1), wenwInfoList.get(2));
			 map.put(restDateList.get(2), wenwInfoList.get(3));
			 map.put(restDateList.get(3), wenwInfoList.get(6));
			 map.put(restDateList.get(4), wenwInfoList.get(8));
			 map.put(restDateList.get(5), wenwInfoList.get(9));
			 map.put(restDateList.get(6), wenwInfoList.get(11));
			 map.put(restDateList.get(7), wenwInfoList.get(13));
			 map.put(restDateList.get(8), wenwInfoList.get(15));
			 map.put(restDateList.get(9), wenwInfoList.get(17));
	//		 wenList.add(map);
		 }
		 if(num==22){
			 map.put(restDateList.get(0), wenwInfoList.get(1));
			 map.put(restDateList.get(1), wenwInfoList.get(4));
			 map.put(restDateList.get(2), wenwInfoList.get(8));
			 map.put(restDateList.get(3), wenwInfoList.get(11));
			 map.put(restDateList.get(4), wenwInfoList.get(15));
			 map.put(restDateList.get(5), wenwInfoList.get(19));
	//		 wenList.add(map);
		 }
//		 if(wenwInfoList.size()>=restDateList.size()){//查询出的文章大于等于天数
//			Map<String,WenwInfo> map=new HashMap<String,WenwInfo>();
//			map.put(restDateList.get(0), wenwInfoList.get(1));
//			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//			 Calendar ca = Calendar.getInstance();
//			 ca.setTime(sdf.parse(restDateList.get(0)));
//			 int index=1;
//			 for(int k=2;k<=wenwInfoList.size();k++){
//				  ca.add(Calendar.DATE, 1);
//	   	  	      Date date2 = ca.getTime();   
//	   	  	      String backTime = sdf.format(date2);
//	   	  	     if(backTime.equals(restDateList.get(index))){
//	   	  	    	map.put(restDateList.get(index), wenwInfoList.get(k));
//	   	  	    	index++;
//	   	  	       }
//			}
//	        wenList.add(map);
//		}
		 resPara.setWenList(map);
	}
}
